package com.wpt.main.servlet;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Servlet implementation class DownFileServlet
 * 下载文件servlet
 * @author xpn
 * @date 2011/3/30 11:14 AM
 */
public class DownFileServlet extends BaseServlet {
	private static final long serialVersionUID = 1L;
       
	@Override
	protected void operator(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		request.setCharacterEncoding("utf-8");
		String path = request.getParameter("path");
		String fileName = path.substring(path.lastIndexOf(File.separator) + 1, path.length());
		String type = fileName.split("[.]")[1];
		File file = new File(path);
		response.setContentType("." + type + ";charset=utf-8");
		response.setContentLength((int)file.length());
		response.setHeader("Content-Disposition", "attachment;filename=" + java.net.URLEncoder.encode(fileName, "utf-8"));
		boolean IEVersion6_0 = (request.getHeader("User-Agent").indexOf("MSIE 6.0") > 0);
		if(IEVersion6_0) {
			response.setHeader("Content-Disposition", "filename=" + java.net.URLEncoder.encode(fileName, "utf-8"));
		}
		ServletOutputStream os = response.getOutputStream();
		FileInputStream fs = new FileInputStream(file);
		byte[] content = new byte[1024];
		int i = -1;
		while((i = fs.read(content)) != -1)
		{
			os.write(content, 0, i);
			os.flush();
		}
		fs.close();
		os.close();
	}
}
